package com.ems.servlet;

import com.ems.dao.AttendanceDAO;
import com.ems.dao.EmployeeDAO;
import com.ems.model.Attendance;
import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/attendance")
public class AttendanceServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        try {
            AttendanceDAO attendanceDAO = new AttendanceDAO();
            EmployeeDAO employeeDAO = new EmployeeDAO();

            if ("add".equals(action)) {
                Attendance attendance = createAttendanceFromRequest(request);

                if (attendanceDAO.addAttendance(attendance)) {
                    response.sendRedirect("attendance?action=list");
                } else {
                    request.setAttribute("error", "添加考勤记录失败");
                    request.getRequestDispatcher("admin/attendance.jsp").forward(request, response);
                }
            } else if ("update".equals(action)) {
                Attendance attendance = createAttendanceFromRequest(request);

                if (attendanceDAO.updateAttendance(attendance)) {
                    response.sendRedirect("attendance?action=list");
                } else {
                    request.setAttribute("error", "更新考勤记录失败");
                    request.getRequestDispatcher("admin/attendance.jsp").forward(request, response);
                }
            } else if ("delete".equals(action)) {
                int attendanceId = Integer.parseInt(request.getParameter("attendanceId"));

                if (attendanceDAO.deleteAttendance(attendanceId)) {
                    response.sendRedirect("attendance?action=list");
                } else {
                    request.setAttribute("error", "删除考勤记录失败");
                    request.getRequestDispatcher("admin/attendance.jsp").forward(request, response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "操作失败，请稍后再试");
            request.getRequestDispatcher("admin/attendance.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        try {
            AttendanceDAO attendanceDAO = new AttendanceDAO();
            EmployeeDAO employeeDAO = new EmployeeDAO();

            if ("list".equals(action)) {
                List<Attendance> attendances = attendanceDAO.getAllAttendances();
                request.setAttribute("attendances", attendances);
                request.setAttribute("employees", employeeDAO.getAllEmployees());
                request.getRequestDispatcher("admin/attendance.jsp").forward(request, response);
            } else if ("view".equals(action)) {
                int attendanceId = Integer.parseInt(request.getParameter("attendanceId"));
                Attendance attendance = attendanceDAO.getAttendanceById(attendanceId);
                request.setAttribute("attendance", attendance);
                request.setAttribute("employees", employeeDAO.getAllEmployees());
                request.getRequestDispatcher("admin/attendance_detail.jsp").forward(request, response);
            } else if ("employee".equals(action)) {
                // 员工查看自己的考勤记录
                String empId = request.getParameter("empId");
                List<Attendance> attendances = attendanceDAO.getAttendancesByEmployee(empId);
                request.setAttribute("attendances", attendances);
                request.getRequestDispatcher("employee/attendance.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "操作失败，请稍后再试");
            request.getRequestDispatcher("admin/attendance.jsp").forward(request, response);
        }
    }

    private Attendance createAttendanceFromRequest(HttpServletRequest request) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Attendance attendance = new Attendance();
        attendance.setEmpId(request.getParameter("empId"));
        attendance.setRecordDate(new Date(sdf.parse(request.getParameter("recordDate")).getTime()));
        attendance.setStatus(request.getParameter("status"));
        attendance.setLeaveReason(request.getParameter("leaveReason"));

        String attendanceId = request.getParameter("attendanceId");
        if (attendanceId != null && !attendanceId.isEmpty()) {
            attendance.setAttendanceId(Integer.parseInt(attendanceId));
        }

        return attendance;
    }
}